package net.wanho.config;

import net.wanho.shiro.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-08-23 16:18
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    /**
     * ShiroFilter，对资源进行过滤处理
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 设置过滤规则
        Map<String,String> map = new HashMap<>();
        map.put("/login.jsp", "anon");
        map.put("/user/login", "anon");
        map.put("/user/logout", "anon");
        map.put("/register.jsp", "anon");
        map.put("/user/register", "anon");
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    /**
     * 安全管理器
     */
    @Bean
    public DefaultWebSecurityManager defaultSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    /**
     * 自定义Realm
     */
    @Bean
    public Realm realm(){
        ShiroRealm realm = new ShiroRealm();
        realm.setName("MyRealm");

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1024);

        realm.setCredentialsMatcher(matcher);

        return realm;
    }

}
